package com.ghsc.ghxc.jsb.ui.home.activity

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.ImageView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.alivc.auicommon.common.roombase.Const
import com.alivc.auimessage.listener.InteractionCallback
import com.alivc.auimessage.model.base.InteractionError
import com.aliyun.auiappserver.AppServerTokenManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.cn.appcore.base.BaseVMActivity
import com.cn.appcore.ext.getCompatColor
import com.cn.appcore.ext.loge
import com.cn.appcore.ext.setOnFastChildClickListener
import com.cn.appcore.ext.setSingleClickListener
import com.cn.appcore.ext.showToast
import com.cn.appcore.ext.startKtxActivity
import com.cn.appcore.http.constant.HttpConstant
import com.cn.appcore.utils.GlideUtil
import com.cn.appcore.utils.GsonUtil
import com.cn.appcore.utils.Preference
import com.ghsc.ghxc.jsb.R
import com.ghsc.ghxc.jsb.api.getUserIdRidUrl
import com.ghsc.ghxc.jsb.config.CustKey
import com.ghsc.ghxc.jsb.config.LoginHelper
import com.ghsc.ghxc.jsb.databinding.ActivityEarnIntegralBinding
import com.ghsc.ghxc.jsb.ui.home.adapter.TaskListAdapter
import com.ghsc.ghxc.jsb.ui.home.bean.St
import com.ghsc.ghxc.jsb.ui.home.bean.TasksStateResult
import com.ghsc.ghxc.jsb.ui.home.view.AdvCompletePopView
import com.ghsc.ghxc.jsb.ui.home.view.IntegralRulePopView
import com.ghsc.ghxc.jsb.ui.live.TabLiveVideoActivity
import com.ghsc.ghxc.jsb.ui.my.activity.MyIntegralActivity
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.enums.PopupAnimation
import com.zj.zjsdk.ad.ZjAdError
import com.zj.zjsdk.ad.ZjRewardVideoAd
import com.zj.zjsdk.ad.ZjRewardVideoAdListener
import com.zj.zjsdk.api.v2.rewarded.ZJRewardedAd
import com.zj.zjsdk.api.v2.rewarded.ZJRewardedAdInteractionListener
import com.zj.zjsdk.api.v2.rewarded.ZJRewardedAdLoadListener

/**
 * 项目：GuoHuaJsb
 * 包名：com.ghsc.ghxc.jsb.ui.home.activity
 * 类名：EarnIntegralActivity
 * 创建时间：2024/5/6 20:53
 * 创建人 @author： xiaolin
 * 描述 ：Todo...
 */
class EarnIntegralActivity : BaseVMActivity<EarnIntegralViewModel, ActivityEarnIntegralBinding>() {
    override fun attachLayoutRes(): Int {
        return R.layout.activity_earn_integral
    }

    override fun attachVMClass(): Class<EarnIntegralViewModel>? {
      return EarnIntegralViewModel::class.java
    }

    val userUid: String by Preference(HttpConstant.USER_ID, "")
    private var rules = mutableListOf<String>()  //打开规则
    private val mAdapter = ListAdapter()



    /// 0  未完成 立即打卡
    /// 1  已完成 立即领取
    /// 2  已领取 已完成
    var  pstatus = 0
    ///默认的任务数量
    var  taskCount=5;
    ///当前做了几个任务
    var  cnt=0;

    //广告的回调标识
    var  tradeid="";



    //日常任务list
    private val mAdapterTask: TaskListAdapter by lazy { TaskListAdapter() }
    var rvListTask = arrayListOf<TasksStateResult>()


    override fun initView() {


        binding.rvListTask.layoutManager = LinearLayoutManager(this)
        binding.rvListTask.adapter = mAdapterTask
        mAdapterTask.setNewInstance(rvListTask)


    }


    override fun onResume() {
        super.onResume()
        mViewModel.onRenwuIndexMethod("")

        //获取日常任务、
        mViewModel.onZbTaskListMethod("")
    }

    override fun initData() {
        super.initData()
        binding.rvShop.adapter = mAdapter
        mAdapter.addChildClickViewIds(R.id.act)
        mAdapter.setOnFastChildClickListener { view, position ->
            when (view.id) {
                R.id.act -> {
                    if (TextUtils.isEmpty(mAdapter.getItem(position).url)){
                        showToast("暂未开放")
                        return@setOnFastChildClickListener
                    }
                   startKtxActivity<WebViewActivity>(
                        values = arrayListOf(
                            "url" to mAdapter.getItem(position).url+ getUserIdRidUrl(),
//                            "showBar" to if(mAdapter.getItem(position).ifhide==1) false else true,
                            "showBar" to  true,
                            "title" to mAdapter.getItem(position).title,
                        )
                    )
                }
                else -> {}
            }
        }


    }

    override fun initClickListener() {
        super.initClickListener()
        binding.imgBtnLeft.setOnClickListener {
            finish()
        }
        binding.tvBtnGuiZe.setOnClickListener {
           //打卡规则
            XPopup.Builder(this)
                .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                .customHostLifecycle(lifecycle)
                . dismissOnBackPressed(true)
                .dismissOnTouchOutside(true)
                .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                .asCustom(IntegralRulePopView(this,rules,"打卡规则"))
                .show()
        }

        binding.tvBtnZiChan.setSingleClickListener {
            startActivity(MyIntegralActivity().javaClass)
        }
        binding.tvPstatus.setSingleClickListener {
            onSignIn(pstatus)
        }
        mAdapterTask.addChildClickViewIds(R.id.tvBtnNext)
        mAdapterTask.setOnFastChildClickListener { view, position ->
            if (view.id==R.id.tvBtnNext){
                //日常任务 跳转直播间
                isLoginLive()
            }
        }


    }

    fun  onSignIn(status:Int){
        if(status==0){
            //立即打卡
            ladZhongJian(CustKey.zjJiLi)
        }else if(status==1){
            //立即领取
            mViewModel.onReadyRenwuMethod("")
        }else{
            //已完成
            showToast("当前您已完成今日打卡任务");
        }
    }


    override fun initRequestObserver() {
        super.initRequestObserver()
        mViewModel.apply {
            errorMsg.observe(this@EarnIntegralActivity) {
                showToast(it)
            }
            againLoginMsg.observe(this@EarnIntegralActivity) {
                showToast(CustKey.IN_AGAIN_MSG)
                LoginHelper.startLoginPage()
            }

            onReadyRenwu.observe(this@EarnIntegralActivity){
                //任务领取
                showToast("领取成功")
                mViewModel.onRenwuIndexMethod("")
            }
            onActRenwu.observe(this@EarnIntegralActivity){
                //完成每个广告
                val msg =it.data.data.msg
                val pstatus=it.data.data.pstatus
                XPopup.Builder(this@EarnIntegralActivity)
                    .popupAnimation(PopupAnimation.ScaleAlphaFromCenter  )
                    .customHostLifecycle(lifecycle)
                    . dismissOnBackPressed(true)
                    .dismissOnTouchOutside(true)
                    .navigationBarColor(getCompatColor(R.color.bg_dark_color))
                    .asCustom(AdvCompletePopView(this@EarnIntegralActivity,msg,pstatus,
                        tvBtn={
                            onSignIn(pstatus)
                        }))
                    .show()
                mViewModel.onRenwuIndexMethod("")
            }
            //积分商城
            onRenwuIndex.observe(this@EarnIntegralActivity) {
                binding.jifen.text=it.data.data.jifen.toString()

                if(it.data.data.pstatus==0){
                    binding.tvPstatus.text="立即打卡"
                    binding.tvPstatus.setTextColor(getCompatColor(R.color.app_main))
                    binding.tvPstatus.delegate.backgroundColor = getCompatColor(R.color.white)
                }else if(it.data.data.pstatus==1){
                    binding.tvPstatus.text="立即领取"
                    binding.tvPstatus.setTextColor(getCompatColor(R.color.white))
                    binding.tvPstatus.delegate.backgroundColor = getCompatColor(R.color.app_main)
                }else{
                    binding.tvPstatus.text="已完成"
                    binding.tvPstatus.setTextColor(getCompatColor(R.color.white))
                    binding.tvPstatus.delegate.backgroundColor = getCompatColor(R.color.app_main)
                }
                  pstatus = it.data.data.pstatus
                ///默认的任务数量
                  taskCount=it.data.data.ggcnt
                ///当前做了几个任务
                  cnt=it.data.data.cnt

                rules = it.data.data.rules.toMutableList()
                mAdapter.replaceData(it.data.data.st)
                //广告
                binding.rvAdv.layoutManager = GridLayoutManager(this@EarnIntegralActivity,it.data.data.ggcnt)
                binding.rvAdv.adapter = advListAdapter
                val list = mutableListOf<String>()
                for (i in 0 until it.data.data.ggcnt){
                    list.add("")
                }
                advListAdapter.replaceData(list)
            }
            onZbTaskListData.observe(this@EarnIntegralActivity){
                //获取日常任务
                if (it.data.isNotEmpty()){
                    binding.llTaks.visibility= View.VISIBLE
                    mAdapterTask.replaceData(it.data)
                }else binding.llTaks.visibility= View.GONE
            }
        }
    }



    class ListAdapter : BaseQuickAdapter<St, BaseViewHolder>(R.layout.layout_red_picket_item){
        override fun convert(holder: BaseViewHolder, item: St) {
            GlideUtil.ImageLoad(holder.itemView.context,item.icon,holder.getView(R.id.imgIcon))
            holder.setText(R.id.title,item.title)
                .setText(R.id.memo,item.memo)
                .setText(R.id.act,item.act)

        }
    }
    private val advListAdapter by lazy { AdvListAdapter() }
    inner class AdvListAdapter : BaseQuickAdapter<String, BaseViewHolder>(R.layout.layout_adv_item){
        override fun convert(holder: BaseViewHolder, item: String) {
            loge("当前item=="+holder.position)

            var icon =holder.getView<ImageView>(R.id.icon)
            val index=holder.position+1
            if(index==taskCount){
                if(cnt==index){
                    icon.setImageResource(R.drawable.icon_ka5_f)
                }else  icon.setImageResource(R.drawable.icon_ka5)
            }else{
                if(cnt>=index)
                    icon.setImageResource(R.drawable.icon_hongbao_f)
                else icon.setImageResource(R.drawable.icon_hongbao)
            }

            holder.setText(R.id.tvCnt,   if(cnt>=index) "已完成" else "第${index}个")
                .setTextColor(R.id.tvCnt,if(cnt>=index) getCompatColor(R.color.picture_color_80) else getCompatColor(R.color.app_main))


        }
    }


    private val isRewardCache = true
    private var ad: ZJRewardedAd? = null


    /** zj广告 **/
    private fun ladZhongJian(keyId: String){
        tradeid=""
        // 实时请求
        ZJRewardedAd.loadAd(
            this,
            keyId,
            userUid,
            object : ZJRewardedAdLoadListener {
                /**
                 * @param code 错误码
                 * @param msg  错误信息
                 */
                override fun onError(code: Int, msg: String) {
                    dismissLoading()

                }
                /**
                 * 加载成功
                 * @param rewardedAd 广告对象
                 */
                override fun onAdLoaded(rewardedAd: ZJRewardedAd) {
                    dismissLoading()
                    ad = rewardedAd
                    // 先确认广告有效
                    ad!!.setAdInteractionListener(object : ZJRewardedAdInteractionListener{
                        override fun onRewardedAdShow() {
                           // 激励展示
                            dismissLoading() // 隐藏加载框
                        }

                        override fun onRewardedAdClick() {
                            //激励点击
                        }

                        override fun onRewardedAdShowError(p0: Int, p1: String) {
                            //展示失败
                            dismissLoading() // 隐藏加载框
                        }

                        override fun onRewardVerify(tradeId: String) {
                            //奖励
                            tradeid=tradeId
                        }

                        override fun onRewardedAdClose() {
                           // 关闭
                            if (!TextUtils.isEmpty(tradeid)){
                                val map: HashMap<String, Any> = HashMap()
                                map["tradeid"] = tradeid
                                GsonUtil.mapToJsonStrObjEncryption(map)?.let { it1 -> mViewModel.onActRenwuMethod(it1) }
                            }
                        }

                    })
                    // 展示
                    ad!!.show(this@EarnIntegralActivity)
                }
            })

    }


    //Add否登录直播。然后跳转直播列表
    private fun isLoginLive(){
        var bundle =Bundle()
        bundle.putInt("index" ,0)
        startActivity(TabLiveVideoActivity().javaClass,bundle)
    }

}